package com.hmdp.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.BooleanUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.dto.Result;
import com.hmdp.entity.RedisData;
import com.hmdp.entity.Shop;
import com.hmdp.mapper.ShopMapper;
import com.hmdp.service.IShopService;
import com.hmdp.utils.CacheClient;
import com.hmdp.utils.RedisConstants;
import com.hmdp.utils.SystemConstants;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.geo.*;
import org.springframework.data.redis.connection.RedisGeoCommands;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Service
public class ShopServiceImpl extends ServiceImpl<ShopMapper, Shop> implements IShopService {

    @Autowired
    private StringRedisTemplate strRedisTemplate;

    @Resource
    private CacheClient cacheClient;

    @Override
    public Result queryById(Long id) {
        //缓存穿透
        /*Shop shop = cacheClient.queryWithPassThrough(RedisConstants.CACHE_SHOP_KEY, id, Shop.class, this::getById , RedisConstants.CACHE_SHOP_TTL, TimeUnit.MINUTES);
        if (shop == null)return Result.fail("商铺不存在");*/
        //缓存击穿解决方案
        Shop shop = cacheClient.queryWithLogicalExpire(RedisConstants.CACHE_SHOP_KEY, id, Shop.class, this::getById, RedisConstants.LOCK_SHOP_TTL);

        //返回
        return Result.ok(shop);
    }


    private static final ExecutorService CACHE_REBUILD_EXECUTOR = Executors.newFixedThreadPool(10);
    public Shop queryWithLogicalExpire(Long id){
        //使用逻辑过期来解决缓存击穿
        String key = RedisConstants.CACHE_SHOP_KEY + id;
        String shopJson = strRedisTemplate.opsForValue().get(key);
        if (!StrUtil.isBlank(shopJson)){
            //不存在
            return null;
        }
        //命中， 判断是否过期
        RedisData redisData = BeanUtil.toBean(shopJson, RedisData.class);
        Shop shop = BeanUtil.toBean(redisData, Shop.class);
        if (redisData.getExpireTime().isBefore(LocalDateTime.now()) && tryLock(RedisConstants.LOCK_SHOP_KEY + id)){
           //过期开启一个新线程更新缓存
            CACHE_REBUILD_EXECUTOR.submit(()->{
                try {
                    saveShop2Redis(id, 20L);
                } finally {
                    unLock(RedisConstants.LOCK_SHOP_KEY + id);
                }
           });
        }
        return shop;
    }

    public void saveShop2Redis(Long id, Long expireSeconds){
        //查询店铺数据
        Shop shop = getById(id);
        RedisData redisData = new RedisData();
        redisData.setData(shop);
        redisData.setExpireTime(LocalDateTime.now().plusSeconds(expireSeconds));
        //写入redis
        strRedisTemplate.opsForValue().set(RedisConstants.CACHE_SHOP_KEY + id, JSONUtil.toJsonStr(redisData));
    }


    public Shop queryWithMutex(Long id) {
        //从redis查数据
        String shopJson = strRedisTemplate.opsForValue().get(RedisConstants.CACHE_SHOP_KEY + id);
        if (!StrUtil.isBlank(shopJson)) {
            //有数据，直接返回
            return JSONUtil.toBean(shopJson, Shop.class);
        }
        if ("".equals(shopJson)) {
            return null;
        }
        Integer count = 0;
        final Integer maxCount = 10;
        //无数据，获取互斥锁
        try {
            while (!tryLock(RedisConstants.LOCK_SHOP_KEY + id)) {
                Thread.sleep(50);
                shopJson = strRedisTemplate.opsForValue().get(RedisConstants.CACHE_SHOP_KEY + id);
                if (!StrUtil.isBlank(shopJson)) {
                    //有数据，直接返回
                    return JSONUtil.toBean(shopJson, Shop.class);
                }
                if ("".equals(shopJson)) {
                    return null;
                }
                if (++count > maxCount) {
                    throw new RuntimeException("获取锁失败");
                }
            }
            //获取锁成功，查询数据库
            Shop shop = getById(id);
            //没数据，返回错误
            if (shop == null) {
                //防止缓存穿透
                strRedisTemplate.opsForValue().set(RedisConstants.CACHE_SHOP_KEY + id, "", RedisConstants.CACHE_NULL_TTL, TimeUnit.MINUTES);
                return null;
            }
            //把数据保存到Redis
            strRedisTemplate.opsForValue().set(RedisConstants.CACHE_SHOP_KEY + id, JSONUtil.toJsonStr(shop), RedisConstants.CACHE_NULL_TTL, TimeUnit.MINUTES);
            return shop;
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        } finally {
            unLock(RedisConstants.LOCK_SHOP_KEY + id);
        }
    }

    /*缓存穿透解决方案*/
    public Shop queryWithPassThrough(Long id) {
        //从redis查数据
        String shopJson = strRedisTemplate.opsForValue().get(RedisConstants.CACHE_SHOP_KEY + id);
        if (!StrUtil.isBlank(shopJson)) {
            //有数据，直接返回
            return JSONUtil.toBean(shopJson, Shop.class);
        }
        //检查是否为空串(防止缓存穿透)
        if ("".equals(shopJson)) {
            return null;
        }
        //没数据，从数据库查数据
        Shop shop = getById(id);
        //没数据，返回错误
        if (shop == null) {
            //防止缓存穿透
            strRedisTemplate.opsForValue().set(RedisConstants.CACHE_SHOP_KEY + id, "", RedisConstants.CACHE_NULL_TTL, TimeUnit.MINUTES);
            return null;
        }
        //把数据保存到Redis
        strRedisTemplate.opsForValue().set(RedisConstants.CACHE_SHOP_KEY + id, JSONUtil.toJsonStr(shop), RedisConstants.CACHE_SHOP_TTL, TimeUnit.MINUTES);
        //返回
        return shop;
    }

    private boolean tryLock(String key) {
        Boolean aBoolean = strRedisTemplate.opsForValue().setIfAbsent(key, "1", 10, TimeUnit.SECONDS);
        return BooleanUtil.isTrue(aBoolean);
    }

    private void unLock(String key) {
        strRedisTemplate.delete(key);
    }

    @Override
    @Transactional
    public Result updateShop(Shop shop) {
        Long id = shop.getId();
        if (id == null) {
            return Result.fail("店铺id不能为空");
        }
        //写数据库
        updateById(shop);
        //删缓存
        strRedisTemplate.delete(RedisConstants.CACHE_SHOP_KEY + shop.getId());
        return Result.ok();
    }

    @Override
    /**
     * 根据类型和可选的坐标位置查询店铺
     *
     * @param typeId 类型ID，用于筛选店铺类型
     * @param current 当前页码，用于分页查询
     * @param x 经度，店铺的地理位置坐标X轴
     * @param y 纬度，店铺的地理位置坐标Y轴
     * @return 返回查询到的店铺结果，包含分页和距离信息
     */
    public Result queryShopByType(Integer typeId, Integer current, Double x, Double y) {
        // 当坐标参数不为空时，根据类型和坐标范围查询Redis中的店铺位置信息
        if (x == null || y == null){
            // 当坐标参数为空时，执行默认的分页查询
            Page<Shop> page = query()
                    .eq("type_id", typeId)
                    .page(new Page<>(current, SystemConstants.DEFAULT_PAGE_SIZE));
            // 返回查询结果
            return Result.ok(page.getRecords());
        }
        // 按照类型和坐标范围查询Redis
        String key = RedisConstants.SHOP_GEO_KEY + typeId;
        Circle circle = new Circle(new Point(x, y), new Distance(10, RedisGeoCommands.DistanceUnit.KILOMETERS));
        // 设置查询时返回距离，并按距离升序排序
        RedisGeoCommands.GeoRadiusCommandArgs args = RedisGeoCommands.GeoRadiusCommandArgs.newGeoRadiusArgs().includeDistance().sortAscending();
        GeoResults<RedisGeoCommands.GeoLocation<String>> radius = strRedisTemplate.opsForGeo().radius(key, circle, args);
        if (radius == null){
            // 如果查询结果为空，返回空结果
            return Result.ok();
        }
        // 构建查询参数，用于MySQL查询时的FIELD函数排序
        StringBuilder param = new StringBuilder();
        List<Double> distanceList = new ArrayList<>();
        for (GeoResult<RedisGeoCommands.GeoLocation<String>> location : radius) {
            String shopId = location.getContent().getName();
            param.append(",").append(shopId);
            //获取距离
            double distance = location.getDistance().getValue();
            String unit = location.getDistance().getUnit();
            if ("km".equals(unit))distance *= 1000;
            distanceList.add(distance);
        }
        // 执行分页查询，并按照Redis中的顺序排序
        List<Shop> result = query()
                .eq("type_id", typeId)
                .last("ORDER BY FIELD(id" + param + ")")
                .page(new Page<>(current, SystemConstants.DEFAULT_PAGE_SIZE)).getRecords();
        // 为查询结果添加距离信息
        for (int i = 0; i < result.size(); i++) {
            result.get(i).setDistance(distanceList.get(i));
        }
        // 返回排序后的查询结果
        return Result.ok(result);

    }

}
